package com.oktest.measure.media.video

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View

class RecordingProgress : View {
    private val paint = Paint()

    @Volatile
    private var state = State.PAUSE
    private var maxTime = 10000.0f
    private var minTime = 2000.0f
    private var progressColor = -0xff0100
    private var lowMinTimeProgressColor = -0x3d7d8
    private var currTime: Long = 0

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    init {
        paint.apply {
            style = Paint.Style.FILL
            color = lowMinTimeProgressColor
            isAntiAlias = true
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val time = System.currentTimeMillis()
        if (state == State.START) {
            val measuredWidth = measuredWidth
            var top = measuredWidth / 2.0f / maxTime
            val tmp = (time - currTime).toFloat()
            if (tmp >= minTime) {
                paint.color = progressColor
            }
            top *= tmp
            if (top < measuredWidth / 2.0f) {
                canvas.drawRect(top, 0.0f, measuredWidth - top, measuredHeight.toFloat(), paint)
                invalidate()
            }
        } else {
            return
        }
        canvas.drawRect(0.0f, 0.0f, 0.0f, measuredHeight.toFloat(), paint)
    }

    fun setMinRecordingTime(midTime: Float) {
        minTime = midTime
    }

    fun setMaxTime(maxTime: Float) {
        this.maxTime = maxTime
    }

    fun startAnimation() {
        if (state != State.START) {
            state = State.START
            currTime = System.currentTimeMillis()
            invalidate()
            visibility = VISIBLE
            paint.color = lowMinTimeProgressColor
        }
    }

    fun stopAnimation() {
        if (state != State.PAUSE) {
            state = State.PAUSE
            visibility = GONE
        }
    }

    internal enum class State(var code: Int, var message: String) {
        START(1, "开始"), PAUSE(2, "暂停");
    }
}